package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.Exception.vo.ResultVo;
import com.zhentao.pojo.OrderInfo;
import com.zhentao.pojo.OrderItem;
import com.zhentao.pojo.Product;
import com.zhentao.service.OrderInfoService;
import com.zhentao.service.OrderItemService;
import com.zhentao.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private ProductService productService;
    /**
     * 订单列表查询（分页）
     * 支持按状态、时间范围、订单号查询
     */
    @GetMapping("/list")
    public ResultVo list(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer status) {

        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        // 按状态查询
        if (status != null) {
            queryWrapper.eq(OrderInfo::getStatus, status);
        }
        // 按创建时间倒序排序
        queryWrapper.orderByDesc(OrderInfo::getCreateTime);

        Page<OrderInfo> pageParam = new Page<>(page, size);
        Page<OrderInfo> pageModel = orderInfoService.page(pageParam, queryWrapper);
        return ResultVo.success(pageModel);
    }

    /**
     * 获取订单详情（包含订单项）
     */
    @GetMapping("/detail/{id}")
    public ResultVo detail(@PathVariable Long id) {
        OrderInfo orderInfo = orderInfoService.getById(id);
        if (orderInfo == null) {
            return ResultVo.error(404, "订单不存在");
        }

        // 查询订单项
        LambdaQueryWrapper<OrderItem> itemWrapper = new LambdaQueryWrapper<>();
        itemWrapper.eq(OrderItem::getOrderId, id);
        List<OrderItem> orderItems = orderItemService.list(itemWrapper);
        List<String> product = new ArrayList<>();
        for (OrderItem item : orderItems){
            Product product1 = productService.getById(item.getProductId());
            product.add(product1.getName());
        }
        Map<String, Object> result = new HashMap<>();
        result.put("orderInfo", orderInfo);
        result.put("orderItems", orderItems);
        result.put("product", product);
        return ResultVo.success(result);
    }

    /**
     * 订单统计
     * 返回：
     * - 各状态订单数量
     * - 总订单数
     * - 总金额
     * - 今日订单数
     * - 今日交易额
     */
    @GetMapping("/statistics")
    public ResultVo statistics() {
        Map<String, Object> result = new HashMap<>();

        // 统计各状态订单数量
        Map<Integer, Long> statusCount = new HashMap<>();
        for (int i = 0; i <= 4; i++) {
            LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderInfo::getStatus, i);
            long count = orderInfoService.count(wrapper);
            statusCount.put(i, count);
        }
        result.put("statusCount", statusCount);

        // 统计总订单数
        long totalOrders = orderInfoService.count();
        result.put("totalOrders", totalOrders);

        // 统计总金额
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(OrderInfo::getTotalAmount);
        List<OrderInfo> orders = orderInfoService.list(wrapper);
        BigDecimal totalAmount = orders.stream()
                .map(OrderInfo::getTotalAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        result.put("totalAmount", totalAmount);

        // 获取今天的开始时间
        Date today = new Date();
        today.setHours(0);
        today.setMinutes(0);
        today.setSeconds(0);

        // 统计今日订单
        LambdaQueryWrapper<OrderInfo> todayWrapper = new LambdaQueryWrapper<>();
        todayWrapper.ge(OrderInfo::getCreateTime, today);
        long todayOrders = orderInfoService.count(todayWrapper);
        result.put("todayOrders", todayOrders);

        // 统计今日交易额
        BigDecimal todayAmount = orders.stream()
                .filter(order -> order.getCreateTime().after(today))
                .map(OrderInfo::getTotalAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        result.put("todayAmount", todayAmount);

        return ResultVo.success(result);
    }

}
